package com.datamation.swadeshi.view;

import java.util.ArrayList;
import java.util.List;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.adapter.ListViewDataAdapter;
import com.datamation.swadeshi.adapter.MergeAdapter;
import com.datamation.swadeshi.adapter.SetTitleAdapter;
import com.datamation.swadeshi.control.AsyncTaskListener;
import com.datamation.swadeshi.control.ConnectionDetector;
import com.datamation.swadeshi.control.TaskType;
import com.datamation.swadeshi.control.UploadLoading;
import com.datamation.swadeshi.control.UploadPreSales;
import com.datamation.swadeshi.control.UploadVanSales;
import com.datamation.swadeshi.control.data.FTranHedDS;
import com.datamation.swadeshi.control.data.InvDetDS;
import com.datamation.swadeshi.control.data.InvHedDS;
import com.datamation.swadeshi.control.data.OrdDetDS;
import com.datamation.swadeshi.control.data.OrdHedDS;
import com.datamation.swadeshi.model.ContentItem;
import com.datamation.swadeshi.model.InvHed;
import com.datamation.swadeshi.model.OrdDet;
import com.datamation.swadeshi.model.OrdHed;
import com.datamation.swadeshi.model.mapping.LoadingMapper;
import com.datamation.swadeshi.model.mapping.PreSalesMapper;
import com.datamation.swadeshi.model.mapping.VanSalesMapper;
import com.google.gson.Gson;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


@SuppressLint("Recycle") 
public class FragmentManagementTools extends Fragment implements AsyncTaskListener{

	 ArrayList<ContentItem> objects;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		
		getActivity().getActionBar().removeAllTabs();
		getActivity().getActionBar().setNavigationMode(0);
		setHasOptionsMenu(true);
		View rootView = inflater.inflate(R.layout.management_tools, container,false);
		
        //set title
		SetTitleAdapter objTitle =new SetTitleAdapter();
		objTitle.createCutomActionBarTitle("Managment Tools", getActivity());

        objects = new ArrayList<ContentItem>();
        MergeAdapter mergeAdapter = new MergeAdapter();
        //nav drawer icons from resources
        TypedArray icons = getResources().obtainTypedArray(R.array.listView_management_tools_icons); 
        
        objects.add(new ContentItem("Sync", "",icons.getResourceId(0, -1)));
        objects.add(new ContentItem("Upload", "",icons.getResourceId(1, -1)));
        objects.add(new ContentItem("Download Stock", "",icons.getResourceId(2, -1)));
        //objects.add(new ContentItem("Expense", "",icons.getResourceId(3, -1)));
                
        ListViewDataAdapter adapter = new ListViewDataAdapter(getActivity().getApplicationContext(), objects);
        
        ListView lv = (ListView) rootView.findViewById(R.id.listView1);
		       
        mergeAdapter.addAdapter(adapter);
        
        lv.setAdapter(mergeAdapter);
        
        
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view2,
					int position, long id) {
			
				switch (position) {
				case 0:
					{
						
						Toast.makeText(getActivity(), objects.get(position).getName() + " selected", Toast.LENGTH_SHORT).show();
					}
				break;
				case 1:
					{	
						syncDialog(getActivity());
						Toast.makeText(getActivity(), objects.get(position).getName() + " selected", Toast.LENGTH_SHORT).show();
					}
				break;
				case 2:
				{
					Toast.makeText(getActivity(), objects.get(position).getName() + " selected", Toast.LENGTH_SHORT).show();
				}
				break;
				case 3:
				{	
					Toast.makeText(getActivity(), objects.get(position).getName() + " selected", Toast.LENGTH_SHORT).show();
				}
				break;

				}

			}
		});
        
		//back button disable 
				rootView.setFocusableInTouchMode(true);
				rootView.requestFocus();
				rootView.setOnKeyListener(new View.OnKeyListener() {
				        @Override
				        public boolean onKey(View v, int keyCode, KeyEvent event) {
				            Log.i("", "keyCode: " + keyCode);
				            if( keyCode == KeyEvent.KEYCODE_BACK ) {
				            	Toast.makeText(getActivity(),"Back Navigationid is disable", Toast.LENGTH_SHORT).show();
				               // getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
				                return true;
				            }else if ((keyCode == KeyEvent.KEYCODE_HOME)) {
				    			
				    			getActivity().finish();
				    			
				    			return true;

				    		} else {
				                return false;
				            }
				        }
				    });
		return rootView;

	}
	
	//dialog box
	private void syncDialog(final Context context){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure, Do you want to upload data?");

		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							@SuppressWarnings("unchecked")
							public void onClick(DialogInterface dialog, int id) {
							
							boolean connectionStatus = new ConnectionDetector(context).isConnectingToInternet();
							if(connectionStatus == true){
							
								OrdHedDS hedDS = new OrdHedDS(getActivity());
								ArrayList<PreSalesMapper> ordHedList =hedDS.getAllUnSyncOrdHed();
								new UploadPreSales(getActivity(), FragmentManagementTools.this, TaskType.UPLOADSPRESALE).execute(ordHedList);
							
							}else
								Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_LONG).show();

						}
					})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								dialog.cancel();
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onTaskCompleted(TaskType taskType) {
		// TODO Auto-generated method stub
		
		switch (taskType) {
		case UPLOADSPRESALE:
		{
			FTranHedDS fTranHedDS = new FTranHedDS(getActivity());
			ArrayList<LoadingMapper> list =fTranHedDS.getAllUnSyncTranHed();
			new UploadLoading(getActivity(), FragmentManagementTools.this, TaskType.UPLOADLOADING).execute(list);
		}	
		break;
		case UPLOADLOADING:
		{
			InvHedDS  invHedDS = new InvHedDS(getActivity());
			ArrayList<VanSalesMapper> list =invHedDS.getAllUnsynced();
			new UploadVanSales(getActivity(), FragmentManagementTools.this, TaskType.UPLOADVANSALES).execute(list);
		}	
		break;
		default:
			break;
		}
	
	}
	
	
}
